<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <!-- @on-load="onLoad" -->
      <template slot="menuRight">
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permissionList.exportBtn"
          @click="handleExport"
          >导出
        </el-button>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button
          icon="el-icon-view"
          size="small"
          type="text"
          v-if="permissionList.viewBtn"
          @click.stop="goTo(row)"
          >查看
        </el-button>
      </template>
      
      <template slot-scope="{disabled,size}" slot="beginTimeSearch">
        <el-date-picker v-model="search.beginTime" type="date" value-format='yyyy-MM-dd' @change="beginTimeChange" placeholder="请输入 统计开始日期"></el-date-picker>
      </template>
      <template slot-scope="{disabled,size}" slot="endTimeSearch">
        <el-date-picker v-model="search.endTime" type="date" value-format='yyyy-MM-dd' @change="endTimeChange" placeholder="请输入 统计结束日期"></el-date-picker>
      </template>

      <template slot-scope="{}" slot="serviceNoSearch">
        <select-page
          ref="searchSerSelect"
          label="serviceName"
          value="serviceNo"
          :select.sync="search.serviceNo"
          :url="website.searchLink.serviceUrl"
          placeholder-text="服务商"
          filter-key="searchParam"
        ></select-page>
      </template>
      <template slot-scope="{}" slot="orgNoSearch">
        <select-page ref="searchOrgSelect" label="serviceName" value="serviceNo" :select.sync="search.orgNo" :url="website.searchLink.orgUrl" placeholder-text="机构" filter-key="searchParam"></select-page>
      </template>
    </avue-crud>
    <div class="curd-foter">
      <div class="redFontBox">交易总金额：<span class="redFont">{{ exhibition(countData.totalTradAmount) || 0 }}</span> 元</div>
      <div class="redFontBox">交易总笔数：<span class="redFont">{{ exhibition(countData.tradeCount) || 0 }}</span> 笔</div>
      <div class="redFontBox">交易手续费：<span class="redFont">{{ exhibition(countData.totalRFee) || 0 }}</span> 元</div>
      <div class="redFontBox">垫资手续费：<span class="redFont">{{ exhibition(countData.totalRFeeD0) || 0 }}</span> 元</div>
      <div class="redFontBox">总手续费：<span class="redFont">{{ exhibition(countData.totalAllFee) || 0 }}</span> 元</div>

      <div class="redFontBox">服务商交易分润：<span class="redFont">{{ exhibition(countData.totalProfitAmount) || 0 }}</span> 元</div>
      <div class="redFontBox">服务商垫资分润：<span class="redFont">{{ exhibition(countData.totalProfitAmountD0) || 0 }}</span> 元</div>
      <div class="redFontBox">服务商总分润：<span class="redFont">{{ exhibition(countData.allProfitAmount) || 0 }}</span> 元</div>
    </div>
  </basic-container>
</template>

<script>
import {
  getListGroup as getList,
  getListCount,
  getExportGroup
} from "@/api/rb-service/serviceprofit/service_profit_day";
import { mapGetters } from "vuex";
import { downloadFileExcel } from "@/util/util";
import selectPage from "@/components/select-page/select-page";

export default {
  components: {
    selectPage,
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 24,
        columnBtn: false,
        labelWidth: 160, //弹出表单的标题的统一宽度
        searchLabelWidth: 100, //搜索框标题宽度
        menuWidth: 100, //操作栏宽度
        emptyBtnText: "重置",
        column: [
          {
            label: "通道名称",
            prop: "aisleKind",
            type: "select",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "number",
            dicUrl: "/api/blade-system/dict/dictionary?code=aisle_kind",            
            search: true,
            overHidden: true,
            minWidth:80,
            searchOrder: 1,
            display:false,
            hide:true
          },
          {
            label: "支付方式",
            prop: "rptPayType",
            type: "select",
            search: true,
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "number",
            dicUrl: "/api/blade-system/dict/dictionary?code=rpt_pay_type",
            overHidden:true,
            minWidth: 70,
            searchOrder: 2,
            hide:true
          },
          // {
          //   label: "卡类型",
          //   prop: "cardType",
          //   type: "select",
          //   display:false,
          //   overHidden:true,
          //   minWidth: 70,
          //   hide:true,
          //   props: {
          //     label: "dictValue",
          //     value: "dictKey",
          //   },
          //   // dataType: "number",
          //   dicUrl: "/api/blade-system/dict/dictionary?code=card_type",
          //   search: true,
          //   searchOrder: 3
          // },
          // {
          //   label: "客户经理",
          //   prop: "accountManager",
          //   type: "select",
          //   display:false,
          //   overHidden:true,
          //   hide:true,
          //   search: true,
          //   searchOrder: 6,
          //   // dataType: "number",
          //   dicUrl: "/api/rb-oem/oem/trade/pos_trade/customerManager",
          //   dicFormatter:(data)=>{
          //     return data.records
          //   },
          //   filterable:true,
          //   // remote:true,
          //   props: {
          //     label: 'accountManagerName',
          //     value: 'accountManager',
          //     desc:'accountManager'
          //   }
          // },
          {
            label: "服务商编号",
            searchLabel: "服务商",
            prop: "serviceNo",
            type: "select",
            search: true,
            searchOrder: 6,
            span: 24,
            overHidden: true,
            width: 140
          },
          {
            label: "",
            prop: "isSelectChild",
            type: "select",
            multiple: false,
            dataType: "string",
            showColumn: false,
            hide: true,
            search: true,
            searchOrder: 6,
            searchSpan:6,
            searchType: "checkbox",
            searchLabelWidth: "0",
            dicData: [
              {
                label: "包含下级",
                value: 1
              }
            ]
          },
          {
            label: "服务商名称",
            prop: "serviceName",
            type: "input",
            overHidden: true,
            width: 200,
            display: false
          },
          {
            label: "机构编号",
            searchLabel: "机构",
            prop: "orgNo",
            type: "input",
            overHidden:true,
            searchOrder: 7,
            search: true,
            width: 140
          },
          {
            label: "机构名称",
            prop: "orgName",
            type: "input",
            width: 200
          },
          {
            label: "统计日期",
            prop: "dayProfit",
            type: "input",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            overHidden: true,
            width: 100
          },
          {
            label: "订单金额",
            prop: "tradeAmount",
            type: "input",
            overHidden: true,
            minWidth: 92
          },
          {
            label: "交易笔数",
            prop: "tradeCount",
            type: "input",
            minWidth: 92,
            overHidden: true
          },
          {
            label: "交易手续费",
            prop: "totalHandling",
            type: "input",
            overHidden: true,
            minWidth: 92
          },
          {
            label: "垫资手续费",
            prop: "totalHandlingD0",
            type: "input",
            minWidth: 92,
            overHidden: true
          },
          {
            label: "提现手续费",
            prop: "withdrawalFee",
            type: "input",
            overHidden:true,
            minWidth:92
          },
          {
            label: "增收手续费",
            prop: "incrementFee",
            type: "input",
            overHidden:true,
            minWidth:92
          },
          {
            label: "服务商交易分润",
            prop: "handlingProfit",
            type: "input",
            minWidth: 120,
            overHidden: true
          },
          {
            label: "服务商垫资分润",
            prop: "handlingProfitD0",
            type: "input",
            minWidth: 120,
            overHidden: true
          },
          {
            label: "服务商总分润",
            prop: "totalHandlingProfit",
            type: "input",
            minWidth: 95
          },
          {
            label: "统计开始日期",
            prop: "beginTime",
            search: true,
            hide: true,
            display: false
          },
          {
            label: "统计结束日期",
            prop: "endTime",
            search: true,
            hide: true,
            display: false
          }
        ]
      },
      data: [],
      countData: [],
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        viewBtn: this.vaildData(
          this.permission.new_service_profit_day_view,
          false
        ),
        exportBtn: this.vaildData(
          this.permission.new_service_profit_day_export,
          false
        ),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    exhibition() {
      return (val) => {
        if (val == "" || val == undefined) {// || val == "-1"
          return (val = 0);
        } else {
          return val;
        }
      };
    },
  },
  watch: {
    // "search.timeData"(val) {
    //   if (val) {
    //     this.search.beginTime = val[0];
    //     this.search.endTime = val[1];
    //   } else {
    //     this.search.beginTime = "";
    //     this.search.endTime = "";
    //   }
    // }
  },
  methods: {
    beginTimeChange() {
      if(this.search.endTime){
        if(Date.parse(this.search.beginTime) > Date.parse(this.search.endTime)){
          this.$alert('统计开始日期不能大于结束日期', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
          .then(() => (this.search.beginTime = ""))
          .catch(() => (this.search.beginTime = ""))
        }
      }
    },
    endTimeChange() {
      if(this.search.beginTime){
        if(Date.parse(this.search.endTime) < Date.parse(this.search.beginTime)){
          this.$alert('统计结束日期不能小于开始日期', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
          .then(() => (this.search.endTime = ""))
          .catch(() => (this.search.endTime = ""))
        }
      }
    },
    // 页面跳转详情
    goTo(row) {
      let param ={
        dayProfit: row.dayProfit,
        serviceNo: row.serviceNo,
        sourceTenantId: row.sourceTenantId,
        name: row.serviceName + "-服务商日汇总",
        nameTitle: row.serviceName,
        type: "serviceDay"
      }

      if(this.query.aisleKind){
        param.aisleKind = this.query.aisleKind
      }

      if(this.query.rptPayType){
        param.rptPayType = this.query.rptPayType
      }

      this.$router.push({
        path: "/serviceprofit/profit_gather",
        query: {
          ...param
        }
      });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        //   getDetail(this.form.id).then(res => {
        //     this.form = res.data.data;
        //   });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.refreshChange();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.refreshChange();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      // if(this.query.isSelectChildArr){
      //   this.query.isSelectChild = this.query.isSelectChildArr[0];
      // }

      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });

      // 获取统计
      getListCount(Object.assign(params, this.query)).then((res) => {
        this.countData = res.data.data;
      });
    },
    /* 服务商 导出excel */
    handleExport() {
      // if (this.search.timeData[0]) {
      //   this.search.beginTime = this.search.timeData[0];
      // }
      // if (this.search.timeData[1]) {
      //   this.search.endTime = this.search.timeData[1];
      // }
      // if(this.search.isSelectChildArr){
      //   this.search.isSelectChild = this.search.isSelectChildArr[0];
      // }

      let params = {
        ...this.search,
        current: "-1",
        size: "-1",
      };

      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        getExportGroup(params).then(
          (res) => {
            downloadFileExcel(res);
          },
          (error) => {
            window.console.log(error);
          }
        );
      });
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>


<style lang="scss" scoped>
.curd-foter {
  padding-top: 10px;
  display: flex;
  flex-wrap: wrap;
}

.redFontBox {
  margin-right: 40px;
  .redFont {
    color: red;
  }
}
</style>

